package com.pks.datacenter.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import lombok.Data;

@Data
public class CascaderDto implements Serializable {

	private static final long serialVersionUID = 8253835086500226795L;
	
	private Long id;
	private Long pid;
	private String value;
	private String label;
	private List<CascaderDto> children;
	private Long count;


	public CascaderDto() {
		super();
	}
	
	public CascaderDto(Long id, Long pid, String value, String label) {
		super();
		this.id = id;
		this.pid = pid;
		this.value = value;
		this.label = label;
	}
	
	
	
	/** 集合数据转换为树形数据（根节点的 pid 必须为 null） */
	public static List<CascaderDto> convertTree(List<CascaderDto> list) {
		List<CascaderDto> result = new ArrayList<CascaderDto>();
		if (list != null && list.size() > 0) {
			for (CascaderDto c : list) {
				c.setChildren(null);
			}
			for (CascaderDto c : list) {
				if (c.getPid() == null) {
					addChilds(c, list);
					result.add(c);
				}
			}
		}
		return result;
	}
	
	private static void addChilds(CascaderDto link, List<CascaderDto> list) {
		if (link != null && list != null) {
			Long cou = 0L;
			for (CascaderDto c : list) {
				if (c.getPid() != null && c.getPid().equals(link.getId())) {
					List<CascaderDto> chi = (List<CascaderDto>) link.getChildren();
					if (chi == null) {
						chi = new ArrayList<CascaderDto>();
					}
					addChilds(c, list);
					chi.add(c);
					if (c.getCount() != null && c.getCount() != 0) {
						cou += c.getCount();
					}
					link.setChildren(chi);
					link.setCount(cou);
				}
			}
		}
	}
	
	
}
